<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/9/7 0007
 * Time: 9:24
 */

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Role;
use App\Models\Permission;
use DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Auth;
use Maatwebsite\Excel\Facades\Excel;



class ExcelController extends Controller
{
    //yyl 获取用户信息并存入数组
    protected function sheetUser()
    {
        $result = array();
        $sheetTitle = array(
            "姓名",
            "手机号",
            "邮箱",
            "地址",
            "身份证号",
            "注册时间",
        );
        array_push($result, $sheetTitle);
        $sheetData = User::select('users.name','users.mobile','users.email','users.address','users.idNo','users.created_at')
            ->leftJoin('role_user', 'role_user.user_id', '=', 'users.id')
            ->leftJoin('roles', 'roles.id', '=', 'role_user.role_id')
            ->where('roles.name', '<>', 'admin')
            ->get();
        for ($i = 0; $i < count($sheetData); $i++) {
            $sheetRow = array();
            array_push($sheetRow, $sheetData[$i]->name);
            array_push($sheetRow, $sheetData[$i]->mobile);
            array_push($sheetRow, $sheetData[$i]->email);
            array_push($sheetRow, $sheetData[$i]->address);
            array_push($sheetRow, $sheetData[$i]->idNo);
            array_push($sheetRow, $sheetData[$i]->created_at);
            array_push($result, $sheetRow);
        }
        return $result;
    }
    /*
     * yyl  excel导出方法实现
     */
    public function postExcelOutput(Request $request)
    {
        $inputData = $request->all();

        $rules = array(
            'subject' => 'required'
        );
        $validator = Validator::make($inputData, $rules);

        if ($validator->fails()) {
            die('有数据格式错误, 请仔细检查');
        }

        switch ($inputData['subject']) {
            case 'user':
                //用户信息
                $sheetData = $this->sheetUser();
                break;
            default:
                echo '不存在此表的导出方法, 请联系管理员';
                die;
        }

        Excel::create($inputData['subject'], function ($excel) use ($sheetData) {
            $excel->sheet('Sheetname', function ($sheet) use ($sheetData) {
                $sheet->fromArray($sheetData, null, 'A1', true, false);
            });
        })->store('xls', base_path('public/assets/excel'));
        echo 'assets/excel/' . $inputData['subject'] . '.xls';
    }
}